package com.yy.device.boot.websocket;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.yy.device.api.web.APIModel;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket handler处理程序
 *
 * @author zhiqiang.sun
 * @date 2022/06/28
 */
@Slf4j
public class WebSocketHandler extends SimpleChannelInboundHandler<Object> {

    private WebSocketServerHandshaker handshaker;

    private final Map<ChannelHandlerContext, String> webSocketContexts = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            //以http请求形式接入，但是走的是websocket
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        } else if (msg instanceof TextWebSocketFrame) {
            //处理websocket客户端的消息
            handlerWebSocketFrame(ctx, (TextWebSocketFrame) msg);
        } else if (msg instanceof PingWebSocketFrame) {
            //心跳处理
            ctx.write(new PongWebSocketFrame(((PingWebSocketFrame) msg).content().retain()));
        } else if (msg instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), ((CloseWebSocketFrame) msg).retain());
            return;
        }
//        System.out.println(msg.text());
//        MonitorVo monitorVo = new MonitorVo();
//        monitorVo.setName(12);
//        monitorVo.setValueLeft(Arrays.asList((short) 1, (short) 2, (short) 3));
//        monitorVo.setValueRight(Arrays.asList((short) 4, (short) 5, (short) 6));
//        ctx.channel().write(new TextWebSocketFrame(JSON.toJSONString(monitorVo)));
    }

    /**
     * 唯一的一次http请求，用于创建websocket
     */
    /**
     * 处理连接
     *
     * @param ctx
     * @param req
     */
    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        HttpHeaders headers = req.headers();
        String realIp = "";
        if (headers.contains("X-Real-IP") && webSocketContexts.containsKey(ctx)) {
            // 不考虑多次代理
            realIp = headers.get("X-Real-IP");
        }

        String remoteAddress = webSocketContexts.get(ctx);
        if (StrUtil.isNotEmpty(remoteAddress) && StrUtil.isNotEmpty(realIp) && !Objects.equals(remoteAddress, realIp)) {
            webSocketContexts.put(ctx, realIp);
        }

        //要求Upgrade为websocket，过滤掉get/Post
        if (!req.decoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) {
            //若不是websocket方式，则创建BAD_REQUEST的req，返回给客户端
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                "ws://" + req.headers().get(HttpHeaderNames.HOST) + req.uri(),
                null, true, 5 * 1024 * 1024);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }

    /**
     * 处理请求
     *
     * @param ctx
     * @param frame
     */
    private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        APIModel apiModel = new APIModel();
        sendMsg(ctx, apiModel);

    }

    public void sendMsg(ChannelHandlerContext ctx, APIModel apiModel) {
        if (ctx == null || apiModel == null || !ctx.channel().isWritable()) {
            return;
        }
        ctx.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(apiModel)));
    }

    /**
     * 发送http响应
     *
     * @param ctx
     * @param req
     * @param res
     */
    private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, DefaultFullHttpResponse res) {
        // 返回应答给客户端
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(),
                    CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        // 如果是非Keep-Alive，关闭连接
        if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //添加连接
        log.info("客户端加入连接：" + ctx.channel());
        ChannelManage.addChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //断开连.
        super.channelInactive(ctx);
        log.info("客户端断开连接：" + ctx.channel());
        ChannelManage.removeChannel(ctx.channel());
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        log.info("客户端断开连接：" + ctx.channel());
        ChannelManage.removeChannel(ctx.channel());
    }
}
